
package com.segment.dcore.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring上下文的获取
 *
 * Created by huapeng.hhp on 2017/3/13.
 */
public class ApplicationContextHolder implements ApplicationContextAware {
	/** 上下文 */
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

    /**
     * 获取bean
     * @param bean  beanId
     * @param clz   类
     * @return
     */
	public static <T> T getBean(String bean, Class<T> clz) {
		if (applicationContext == null) {
			return null;
		} else {
			try {
				return applicationContext.getBean(bean, clz);
			} catch (Exception ex) {
                ex.printStackTrace();
				return null;
			}
		}
	}

    /**
     *  根据beanId查询
     * @param bean
     * @return
     */
	public static Object getBean(String bean) {
		if (applicationContext == null) {
			return null;
		} else {
			try {
				return applicationContext.getBean(bean);
			} catch (Exception ex) {
                ex.printStackTrace();
				return null;
			}
		}
	}
}
